package com.zwface.demo.function.main;

import android.app.Activity;
import android.graphics.Color;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.DialogPlusBuilder;
import com.orhanobut.dialogplus.Holder;
import com.orhanobut.dialogplus.OnClickListener;
import com.orhanobut.dialogplus.ViewHolder;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.zwface.demo.App;
import com.zwface.demo.R;
import com.zwface.demo.base.BaseFragment;
import com.zwface.demo.comm.comm;
import com.zwface.demo.databinding.FragmentMainBinding;
import com.zwface.demo.function.main.event.SelectCoursesEvent;
import com.zwface.demo.function.main.mvvm.MainViewModel;
import com.zwface.demo.greendao.CourseManager;
import com.zwface.demo.greendao.JoinUserWithCourseManager;
import com.zwface.demo.model.db.Course;
import com.zwface.demo.model.db.JoinUserWithCourse;
import com.zwface.demo.utils.DialogHelper;
import com.zwface.demo.utils.SharedPreferenceUtils;
import com.zwface.demo.utils.schedule.ColorUtils;
import com.zwface.demo.utils.schedule.CornerTextView;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import androidx.lifecycle.ViewModelProviders;

/**
 * created by 张中文
 * on 2020/2/3
 * 描述：
 */
public class MainFragment extends BaseFragment<FragmentMainBinding>
{
    private MainViewModel viewModel;
    List<LinearLayout> mWeekViews;
    private int itemHeight;
    private int maxSection = 8;

    @Override
    protected int onLayoutId() {
        return R.layout.fragment_main;
    }

    @Override
    protected boolean onSetEventBus() {
        return true;
    }

    @Override
    protected void onInitBinding(FragmentMainBinding binding) {
        super.onInitBinding(binding);
        viewModel = ViewModelProviders.of(this).get(MainViewModel.class);
    }

    @Override
    protected void onInitComponent() {
        super.onInitComponent();
        initTopbar();
        itemHeight = getResources().getDimensionPixelSize(R.dimen.sectionHeight);

        mWeekViews = new ArrayList<>();
        mWeekViews.add(binding.weekPanel1);
        mWeekViews.add(binding.weekPanel2);
        mWeekViews.add(binding.weekPanel3);
        mWeekViews.add(binding.weekPanel4);
        mWeekViews.add(binding.weekPanel5);
        mWeekViews.add(binding.weekPanel6);
        mWeekViews.add(binding.weekPanel7);

        initWeekNameView();
        initSectionView();
        initWeekCourseView();
        setRefreshListener();
    }

    private void initTopbar(){
        binding.topbar.setTitle("课程表");
        binding.topbar.removeAllRightViews();
        if(viewModel.isTeacher.get()){
            Button rightBtn = binding.topbar.addRightTextButton("添加",R.id.topbar_right_view_button);
            rightBtn.setTextColor(Color.WHITE);
            rightBtn.setOnClickListener(view -> {
                showCourseEditDialog(new Course(),true);
            });
        }else{
            Button rightBtn = binding.topbar.addRightTextButton("选课",R.id.topbar_right_view_button);
            rightBtn.setTextColor(Color.WHITE);
            rightBtn.setOnClickListener(view -> {
                viewModel.showAllCourseDlg(context);
            });
        }
    }

    /**
     * 初始化课程表
     */
    private void initWeekCourseView()
    {
        String userNo = SharedPreferenceUtils.getParam(context,SharedPreferenceUtils.USER_STUNO);
        List<Course>[] courses = CourseManager.getCoursesByUserNo(userNo);
        for (int i = 0; i < mWeekViews.size(); i++) {
            if(courses == null || courses[i]==null)
                continue;
            initWeekPanel(mWeekViews.get(i), courses[i]);
        }
    }

    /**
     * 选课回调
     * @param event
     */
    @Subscribe
    public void onSelectCoursesEvent(SelectCoursesEvent event){
        clearChildView();
        List<Course>[] courses = event.getList();
        for (int i = 0; i < mWeekViews.size(); i++) {
            if(courses == null || courses[i]==null)
                continue;
            initWeekPanel(mWeekViews.get(i), courses[i]);
        }
    }

    /**
     * 下拉刷新
     */
    private void setRefreshListener() {

    }

    /**
     * 顶部周一到周日的布局
     **/
    private void initWeekNameView() {
        for (int i = 0; i < mWeekViews.size() + 1; i++) {
            TextView tvWeekName = new TextView(context);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            lp.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL;
            if (i != 0) {
                lp.weight = 1;
                tvWeekName.setText("周" + intToZH(i));
                if (i == getWeekDay()) {
                    tvWeekName.setTextColor(com.blankj.utilcode.util.ColorUtils.getColor(R.color.theme));
                } else {
                    tvWeekName.setTextColor(Color.parseColor("#4A4A4A"));
                }
            } else {
                lp.weight = 0.8f;
                tvWeekName.setText(getMonth() + "月");
            }
            tvWeekName.setGravity(Gravity.CENTER_HORIZONTAL);
            tvWeekName.setLayoutParams(lp);
            binding.weekNames.addView(tvWeekName);
        }
    }

    /**
     * 左边节次布局，设定每天最多12节课
     */
    private void initSectionView() {
        for (int i = 1; i <= maxSection; i++) {
            TextView tvSection = new TextView(context);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, getResources().getDimensionPixelSize(R.dimen.sectionHeight));
            lp.gravity = Gravity.CENTER;
            tvSection.setGravity(Gravity.CENTER);
            tvSection.setText(String.valueOf(i));
            tvSection.setLayoutParams(lp);
            binding.sections.addView(tvSection);
        }
    }

    /**
     * 当前星期
     */
    public int getWeekDay() {
        int w = Calendar.getInstance().get(Calendar.DAY_OF_WEEK) - 1;
        if (w <= 0) {
            w = 7;
        }
        return w;
    }

    /**
     * 当前月份
     */
    public int getMonth() {
        int w = Calendar.getInstance().get(Calendar.MONTH) + 1;
        return w;
    }

    /**
     * 每次刷新前清除每个LinearLayout上的课程view
     */
    private void clearChildView() {
        for (int i = 0; i < mWeekViews.size(); i++) {
            if (mWeekViews.get(i) != null)
                if (mWeekViews.get(i).getChildCount() > 0)
                    mWeekViews.get(i).removeAllViews();
        }
    }

    public void initWeekPanel(LinearLayout ll, List<Course> data) {

        if (ll == null || data == null || data.size() < 1)
            return;
        Course firstCourse = data.get(0);
        for (int i = 0; i < data.size(); i++) {
            final Course courseModel = data.get(i);

            if (courseModel.getSection() == 0 || courseModel.getSectionSpan() == 0)
                return;
            FrameLayout frameLayout = new FrameLayout(context);

            CornerTextView tv = new CornerTextView(context,
                    ColorUtils.getCourseBgColor(courseModel.getCourseFlag()),
                    SizeUtils.dp2px(3f));
            LinearLayout.LayoutParams frameLp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    itemHeight * courseModel.getSectionSpan());
            LinearLayout.LayoutParams tvLp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT);

            if (i == 0) {
                frameLp.setMargins(0, (courseModel.getSection() - 1) * itemHeight, 0, 0);
            } else {
                frameLp.setMargins(0, (courseModel.getSection() - (firstCourse.getSection() + firstCourse.getSectionSpan())) * itemHeight, 0, 0);
            }
            tv.setLayoutParams(tvLp);
            tv.setGravity(Gravity.CENTER);
            tv.setTextSize(12);
            tv.setTextColor(Color.parseColor("#FFFFFF"));
            tv.setText(courseModel.getCourseName() + "\n @" + courseModel.getClassRoom());

            frameLayout.setLayoutParams(frameLp);
            frameLayout.addView(tv);
            frameLayout.setPadding(2, 2, 2, 2);
            ll.addView(frameLayout);
            firstCourse = courseModel;
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(viewModel.isTeacher.get()){
                        showCourseEditDialog(courseModel,false);
                    }
                }
            });
            tv.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    showCourseDelDialog(courseModel);
                    return false;
                }
            });
        }
    }

    /**
     * 删除课程弹窗
     * @param course
     */
    private void showCourseDelDialog(Course course) {
        new QMUIDialog.MessageDialogBuilder(getActivity())
                .setTitle("提示")
                .setMessage("确定要删除此课程吗？")
                .setSkinManager(QMUISkinManager.defaultInstance(getContext()))
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, "确定", QMUIDialogAction.ACTION_PROP_POSITIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                        CourseManager.deleteCourse(course.getId());

                        clearChildView();
                        initWeekCourseView();

                        ToastUtils.showShort("删除成功");
                    }
                })
                .create(DialogHelper.mCurrentDialogStyle).show();
    }

    /**
     * 添加/修改课程弹窗
     */
    public void showCourseEditDialog(Course course,Boolean isAdd)
    {
        View contentView = LayoutInflater.from(context).inflate(R.layout.dialog_course_add,null);
        Holder holder = new ViewHolder(contentView);
        EditText et_name = contentView.findViewById(R.id.et_name);
        EditText et_room = contentView.findViewById(R.id.et_room);
        EditText et_week = contentView.findViewById(R.id.et_week);
        EditText et_section = contentView.findViewById(R.id.et_section);
        if(!isAdd){
            et_name.setText(course.getCourseName());
            et_room.setText(course.getClassRoom());
            et_week.setText(course.getWeek()+"");
            et_section.setText(course.getSection()+"");
        }
        DialogPlusBuilder plusBuilder = DialogPlus.newDialog(context)
                .setContentHolder(holder)
                .setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(DialogPlus dialog, View view) {
                        switch (view.getId()){
                            case R.id.btn_save:
                                String courseName = et_name.getText().toString().trim();
                                String courseRoom = et_room.getText().toString().trim();
                                String week = et_week.getText().toString().trim();
                                String section = et_section.getText().toString().trim();
                                if(!comm.ValidationForm(courseName,"请输入课程名")) return;
                                if(!comm.ValidationForm(courseRoom,"请输入教室名")) return;
                                if(!comm.ValidationForm(week,"请输入星期数")) return;
                                if(!comm.ValidationForm(section,"请输入节次")) return;
                                int _week = Integer.parseInt(week);
                                int _section = Integer.parseInt(section);
                                int _sectionSpan = 1;
                                if(_week<1 || _week>7){
                                    ToastUtils.showShort("请输入1-7内的数字");
                                    return;
                                }
                                if(_section<1 || _section>maxSection){
                                    ToastUtils.showShort("请输入1-8内的数字");
                                    return;
                                }
                                if(_sectionSpan <1 || (_section+_sectionSpan-1)>maxSection){
                                    ToastUtils.showShort("一天最多"+maxSection+"节课");
                                    return;
                                }

                                course.setCourseName(courseName);
                                course.setClassRoom(courseRoom);
                                course.setSection(_section);
                                course.setWeek(_week);
                                course.setSectionSpan(_sectionSpan);
                                if(isAdd){
                                    //添加课程
                                    course.setCourseFlag((int) (Math.random() * 10));
                                    Long courseId = CourseManager.addCourse(course);


                                    //添加用户-课程关联信息
                                    String userId = SharedPreferenceUtils.getParam(App.getInstance().getApplicationContext(),SharedPreferenceUtils.USER_ID);
                                    JoinUserWithCourse joinUserWithCourse = new JoinUserWithCourse();
                                    joinUserWithCourse.setCId(courseId);
                                    joinUserWithCourse.setUId(Long.parseLong(userId));
                                    Long joinId = JoinUserWithCourseManager.addJoinUserWithCoutse(joinUserWithCourse);

                                }else{
                                    //修改课程
                                    CourseManager.updateCourse(course);
                                    //不用修改用户-课程关联信息
                                }

                                clearChildView();
                                initWeekCourseView();

                                ToastUtils.showShort("保存成功");
                                dialog.dismiss();
                                break;
                        }
                    }
                });
        plusBuilder.create().show();
    }



    /**
     * 数字转换中文
     */
    public static String intToZH(int i) {
        String[] zh = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
        String[] unit = {"", "十", "百", "千", "万", "十", "百", "千", "亿", "十"};

        String str = "";
        StringBuffer sb = new StringBuffer(String.valueOf(i));
        sb = sb.reverse();
        int r = 0;
        int l = 0;
        for (int j = 0; j < sb.length(); j++) {
            r = Integer.valueOf(sb.substring(j, j + 1));
            if (j != 0)
                l = Integer.valueOf(sb.substring(j - 1, j));
            if (j == 0) {
                if (r != 0 || sb.length() == 1)
                    str = zh[r];
                continue;
            }
            if (j == 1 || j == 2 || j == 3 || j == 5 || j == 6 || j == 7 || j == 9) {
                if (r != 0)
                    str = zh[r] + unit[j] + str;
                else if (l != 0)
                    str = zh[r] + str;
                continue;
            }
            if (j == 4 || j == 8) {
                str = unit[j] + str;
                if ((l != 0 && r == 0) || r != 0)
                    str = zh[r] + str;
                continue;
            }
        }
        if (str.equals("七"))
            str = "日";
        return str;
    }


}
